package com.sanhuo.idms.controller;

import com.sanhuo.idms.SocketServer;
import com.sanhuo.idms.bo.DormHighSearchBO;
import com.sanhuo.idms.bo.DormSaveBO;
import com.sanhuo.idms.entity.*;
import com.sanhuo.idms.service.*;
import com.sanhuo.idms.vo.*;
import com.sanhuo.lib.ExceptionUtil;
import com.sanhuo.lib.exception.GlobalException;
import com.sanhuo.security.contains.State;
import com.sanhuo.security.uitls.UserHolder;
import com.sanhuo.triild.page.Page;
import com.sanhuo.triild.page.PageSearch;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.basic.StringUtil;
import jdk.net.Sockets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.text.ParseException;
import java.util.*;

import static java.awt.SystemColor.info;

@RequestMapping("dorm")
@RestController
public class DormController {
    //发送数据缓冲区
    private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);

    @Autowired
    private TungService tungService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private DormService dormService;
    @Autowired
    private DormElectricService dormElectricService;
    @Autowired
    private ElectricScheduleDayService dayService;
    @Autowired
    private ElectricSheduleWeekService weekService;
    @Autowired
    private DeviceStateService deviceStateService;
    @Autowired
    private DormIpService dormIpService;

    @RequestMapping("changeState")
    public void changDeviceState(String dormId, Boolean state) throws IOException {
        DormIp dormIp = dormIpService.findByDormId(dormId);
        DeviceState deviceState = deviceStateService.findByDorm(dormId);
        ExceptionUtil.throwException(dormIp == null || StringUtil.isBlank(dormIp.getIp()), "通信设备未连接!");
        SocketChannel channel = SocketServer.map.get(dormIp.getIp());
        ExceptionUtil.throwException(channel == null, "通信设备未连接!");
        String sendText;
        if (state) {
            sendText = String.valueOf(1);
            deviceState.setState(true);
            deviceState.setUpdateTime(new Date());
            deviceStateService.update(deviceState);
        } else {
            sendText = String.valueOf(0);
            deviceState.setState(false);
            deviceState.setUpdateTime(new Date());
            deviceStateService.update(deviceState);
        }
        sBuffer.clear();
        sBuffer.put((sendText).getBytes());
        sBuffer.flip();
        //输出到通道
        if (channel.write(sBuffer) < 0) {
            throw new GlobalException("设备通信失败!");
        }
        channel.register(SocketServer.selector, SelectionKey.OP_READ);
    }


    @RequestMapping("device")
    public Boolean getLightState(String dormId) {
        DeviceState state = deviceStateService.findByDorm(dormId);
        if (state == null || state.getState() == null) {
            return false;
        }
        return state.getState();
    }

    /**
     * 返回所有的栋跟宿舍号跟床位
     *
     * @return
     * @throws IllegalAccessException
     */
    @RequestMapping("tungAndRoom")
    public TungAndRoomPageVO findAllDorm() throws IllegalAccessException {
        TungAndRoomPageVO result = new TungAndRoomPageVO();
        List<Tung> tungs = tungService.findAll();
        List<Room> rooms = roomService.findAll();
        List<TungVo> tungVos = new ArrayList<>();
        List<RoomVO> roomVOS = new ArrayList<>();

        for (Tung tung : tungs) {
            TungVo tungVo = new TungVo();
            BeanUtil.copyBean(tung, tungVo);
            tungVos.add(tungVo);
        }
        for (Room room : rooms) {
            RoomVO roomVO = new RoomVO();
            BeanUtil.copyBean(room, roomVO);
            roomVOS.add(roomVO);
        }
        List<String> bunks = Arrays.asList("1", "2", "3", "4");
        result.setBunks(bunks);
        result.setRooms(roomVOS);
        result.setTungs(tungVos);
        return result;
    }

    @RequestMapping("tung/save")
    public void saveTung(Integer tungNum) {
        tungService.save(UserHolder.user(), tungNum);
    }

    @RequestMapping("room/save")
    public void saveRoom(Integer roomNum) {
        roomService.save(UserHolder.user(), roomNum);
    }

    @RequestMapping("save")
    public void save(DormSaveBO bo) throws IllegalAccessException {
        dormService.insert(UserHolder.user(), bo);
    }

    @RequestMapping("list")
    public Page<DormPageVO> listAll(DormHighSearchBO bo, PageSearch pageSearch) {
        return dormService.listAll(bo, pageSearch);
    }


    @RequestMapping("detail")
    public DormDetailVO findOne(String id) {
        return dormService.detail(id);
    }

    @RequestMapping("day")
    public List<Double> dayConsume(String dormId) {
        List<Double> result = dayService.todayConsume(dormId);
        return result;
    }

    @RequestMapping("week")
    public List<Double> weekConsume(String dormId) throws ParseException {
        return weekService.consumeWeek(dormId);
    }

    @RequestMapping("analysis/tung")
    public List<TungComsumeAnalysisVO> analysisByTung() {
        List<Tung> tungs = tungService.findAll();
        List<TungComsumeAnalysisVO> result = new ArrayList<>();
        for (Tung tung : tungs) {
            result.add(dormElectricService.anslysisTung(tung.getId()));
        }
        return result;
    }

}
